using System.Net.Http.Headers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using LiveHub.Share.DataModels;
using LiveHub.WebApi.Models;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;

namespace LiveHub.WebApi.Controllers;

[Route("api/[controller]")]
[ApiController]
public class UserController(
    HubContext context,
    JwtHelper jwtHelper,
    IHttpClientFactory httpClientFactory,
    IHttpContextAccessor httpContextAccessor) : ControllerBase
{
    
    [TokenActionFilter]
    [Authorize]
    [HttpGet]
    public async Task<ActionResult<UserModel>> GetData()
    {
        var member = httpContextAccessor.HttpContext?.User.GetUser();
        if (member == null) return NotFound();
        member = await context.Users.Include(x => x.Groups)
            .FirstOrDefaultAsync(x => x.UserId == member.UserId && x.UserName == member.UserName);
        if (member == null) return NotFound();

        return member;
    }


    [HttpPost]
    public async Task<ActionResult<string>> Login(LoginModel login)
    {
        var user = await context.Users.FirstOrDefaultAsync(x => x.UserId == login.Id && x.UserName == login.Name);
        if (user != null) return jwtHelper.GetMemberToken(user);

        var client = httpClientFactory.CreateClient();
        var response = await client.PostAsJsonAsync("https://www.xauat.site/api/Member/Login", login);
        if (!response.IsSuccessStatusCode) return NotFound();

        var Jwt = await response.Content.ReadAsStringAsync();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Jwt);
        response = await client.GetAsync("https://www.xauat.site/api/Member/GetData");

        if (!response.IsSuccessStatusCode) return NotFound();

        var json = await response.Content.ReadAsStringAsync();
        var userData = JsonConvert.DeserializeObject<UserModel>(json);
        if (userData is null) return NotFound();
        context.Users.Add(userData);
        var ios = await context.Groups.Include(groupModel => groupModel.Users).FirstAsync();
        ios.Users.Add(userData);
        await context.SaveChangesAsync();
        return jwtHelper.GetMemberToken(userData);
    }
}

[Serializable]
public class LoginModel
{
    public string Name { get; set; } = "";
    public string Id { get; set; } = "";
}